package com.heima.behavior.v1.controller;

import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import static com.heima.common.constants.Constants.*;

@RestController
public class BehaviorController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 点赞
     *
     * @return
     */
    @PostMapping("/api/v1/likes_behavior")
    public ResponseResult likes(@RequestBody LikesBehaviorDto dto) {
        if (dto == null) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //文章id
        Long articleId = dto.getArticleId();
        //用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        //设备id
        String equipmentId = dto.getEquipmentId();
        String key = getLikedKey(userId + "", equipmentId, articleId + "");
        //点赞,取消点赞
        Integer operation = dto.getOperation();
        if (!StringUtils.isEmpty(equipmentId)) {
            //String key = ""+dto.getArticleId()+equipmentId;
            //如果设备不为空,那就是游客
            redisTemplate.opsForHash().put(key, "ISLIKE", operation.toString());
            //文章的点赞数量+1
            //redisTemplate.opsForHash().increment(MAP_KEY_ARTICLE_COUNT, articleId, 1);
        }
        if (userId != null) {
            //  String key = ""+dto.getArticleId()+userId;
            //如果userId不为空,那就是用户
            redisTemplate.opsForHash().put(key, "ISLIKE",operation.toString());
            //文章的点赞数量+1
            // redisTemplate.opsForHash().increment(MAP_KEY_ARTICLE_COUNT, articleId, 1);
        }

        return ResponseResult.ok();
    }


    private String getLikedKey(String likedUserId, String equipmentId, String likedArticleId) {

        StringBuilder builder = new StringBuilder();
        if (StringUtils.isEmpty(likedUserId)) {
            builder.append(likedArticleId);
            builder.append(likedUserId);
        }else {
            builder.append(likedArticleId);
            builder.append(equipmentId);
        }

        return builder.toString();
    }

    /**
     * 用户不喜欢
     *
     * @param dto
     * @return
     */
    @PostMapping("/api/v1/unlike_behavior")
    public ResponseResult unLike(@RequestBody UnLikesBehaviorDto dto) {
        //判断dto正确性
        if (ObjectUtils.isEmpty(dto.getArticleId())) {
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前用户
        Integer userId = UserThreadLocalUtils.getUserId();
        if(ObjectUtils.isEmpty(userId)){
            //未登录用户
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取articleId
        Long articleId = dto.getArticleId();
        //拼接key
        String REDIS_KEY = "" + articleId + userId;
        redisTemplate.opsForHash().put(REDIS_KEY, REDIS_KEY_ISUNLIKE, dto.getType());
        return ResponseResult.ok();
    }


    /**
     * 阅读
     * @param dto
     * @return
     */
    @PostMapping("/api/v1/read_behavior")
    public ResponseResult readBehavior(@RequestBody ReadBehaviorDto dto){
        Integer userId = UserThreadLocalUtils.getUserId();
        Long articleId = dto.getArticleId();
        String key = ""+articleId+userId;
        //查询Redis中的阅读次数
        String ValueRedis = (String) redisTemplate.opsForHash().get(key, REDIS_KEY_READ_COUNT);
        if (StringUtils.isEmpty(ValueRedis)){
            //如果不存在创建一个新的
            redisTemplate.opsForHash().put(key,REDIS_KEY_READ_COUNT,dto.getCount()+"");
            return ResponseResult.ok();
        }
        //如果存在就进行加一
        Integer ValueRedisInt = Integer.valueOf(ValueRedis);
        ValueRedisInt++;
        redisTemplate.opsForHash().put(key,REDIS_KEY_READ_COUNT,""+ValueRedisInt);
        return ResponseResult.ok();
    }

}
